package com.btex.app;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.security.rp.RPSDK;
import com.btex.app.entity.GetInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.PermissionUtils;
import com.btex.app.tools.SharedPreferencesUtil;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.taobao.windvane.config.GlobalConfig.context;

public class AuthenticationInformationAcitvity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.activity_authentication_information_dengji)
    TextView mActivityAuthenticationInformationDengji;
    @BindView(R.id.activity_authentication_information_name)
    TextView mActivityAuthenticationInformationName;
    @BindView(R.id.activity_authentication_information_type)
    TextView mActivityAuthenticationInformationType;
    @BindView(R.id.activity_authentication_information_number)
    TextView mActivityAuthenticationInformationNumber;
    @BindView(R.id.activity_authentication_information_c)
    TextView mActivityAuthenticationInformationC;
    @BindView(R.id.activity_authentication_information_lin)
    LinearLayout mActivityAuthenticationInformationLin;
    @BindView(R.id.activity_authentication_information_lin_show)
    LinearLayout mActivityAuthenticationInformationLinShow;
    @BindView(R.id.activity_authentication_information_tv_error)
    TextView mActivityAuthenticationInformationTvError;
    @BindView(R.id.activity_authentication_information_tv_error_agin)
    TextView mActivityAuthenticationInformationTvErrorAgin;

    @BindView(R.id.activity_authentication_information_c2)
    TextView activity_authentication_information_c2;
    private MicroAVLIDialog mMicroAVLIDialog;
    private GetInfo mGetInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authentication_information_acitvity);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mTvTitle.setText(getString(R.string.s_autonym));
        mMicroAVLIDialog = new MicroAVLIDialog(this);
        getInfo();
    }


    private void initviews(GetInfo info) {


        String status = info.getData().getStatus();

        if ("0".equals(status)) {

            mActivityAuthenticationInformationLin.setVisibility(View.VISIBLE);
            mActivityAuthenticationInformationLinShow.setVisibility(View.GONE);
            mActivityAuthenticationInformationTvErrorAgin.setVisibility(View.INVISIBLE);
            if (info.getData().getProve_level().equals("C1")) {
                mActivityAuthenticationInformationTvError.setText("C1审核中.....");
            } else if (info.getData().getProve_level().equals("C2")) {
                mActivityAuthenticationInformationTvError.setText("C2审核中.....");
            } else {

            }


        } else {

            mActivityAuthenticationInformationLin.setVisibility(View.GONE);
            mActivityAuthenticationInformationLinShow.setVisibility(View.VISIBLE);

            String prove_info = info.getData().getProve_level();

            if (prove_info.equals("C0")) {
                mActivityAuthenticationInformationC.setVisibility(View.VISIBLE);
                mActivityAuthenticationInformationC.setText("去认证C1>>>");
                mActivityAuthenticationInformationDengji.setText("C0");
                mActivityAuthenticationInformationName.setText("未认证");
                mActivityAuthenticationInformationType.setText("未认证");
                mActivityAuthenticationInformationNumber.setText("未认证");
                activity_authentication_information_c2.setVisibility(View.GONE);

            } else if (prove_info.equals("C1")) {
//              去c2
                mActivityAuthenticationInformationC.setVisibility(View.VISIBLE);
                setInfo(info);
                mActivityAuthenticationInformationC.setText("去认证C2>>>");
                activity_authentication_information_c2.setVisibility(View.VISIBLE);
                activity_authentication_information_c2.setText("上传照片认证C2>>>");


            } else {

                if ("0".equals(status)) {
                    mActivityAuthenticationInformationLin.setVisibility(View.VISIBLE);
                    mActivityAuthenticationInformationLinShow.setVisibility(View.GONE);
                    mActivityAuthenticationInformationTvError.setText(info.getData().getProve_info().getErr_tips());


                } else if ("-1".equals(status)) {

                    mActivityAuthenticationInformationLin.setVisibility(View.VISIBLE);
                    mActivityAuthenticationInformationLinShow.setVisibility(View.GONE);
                    mActivityAuthenticationInformationTvError.setText("审核失败原因:" + "\n" + "\n" + info.getData().getProve_info().getErr_tips());
                    mActivityAuthenticationInformationC.setVisibility(View.INVISIBLE);
//                    setInfo(info);
                } else {

                    mActivityAuthenticationInformationLin.setVisibility(View.GONE);
                    mActivityAuthenticationInformationLinShow.setVisibility(View.VISIBLE);
                    setInfo(info);
                }
//

            }

        }


    }

    private void setInfo(GetInfo info) {

        GetInfo.DataBean.ProveInfoBean prove_info1 = info.getData().getProve_info();
        String true_name = prove_info1.getTrue_name();
        String idcard_type = prove_info1.getIdcard_type();
        String idcard_no = prove_info1.getIdcard_no();
        String prove_level = info.getData().getProve_level();
        mActivityAuthenticationInformationDengji.setText(prove_level);
        mActivityAuthenticationInformationName.setText(true_name);

        mActivityAuthenticationInformationNumber.setText(idcard_no);

        if ("1".equals(idcard_type)) {
            mActivityAuthenticationInformationType.setText("身份证");
        } else if ("2".equals(idcard_type)) {
            mActivityAuthenticationInformationType.setText("军官证");
        } else {
            mActivityAuthenticationInformationType.setText("护照");
        }

    }

    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {


    }


    @OnClick({R.id.iv_back, R.id.activity_authentication_information_c, R.id.activity_authentication_information_tv_error_agin, R.id.activity_authentication_information_c2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:

                finish();
                break;
            case R.id.activity_authentication_information_c:

                if (mGetInfo != null) {
                    String prove_level = mGetInfo.getData().getProve_level();
                    if (prove_level.equals("C0")) {

//                       去认证c1
                        startActivity(new Intent(this, CertificationOneActivity.class));

                    } else if (prove_level.equals("C1")) {

                        getData();

                    } else {

                    }
                }


                break;

            case R.id.activity_authentication_information_tv_error_agin:

                getData();

                break;

            case R.id.activity_authentication_information_c2:

//                Intent intent = new Intent();
//                intent.setAction("android.intent.action.VIEW");
//                Uri content_url = Uri.parse("https://btex.me/home/prove_tpl?window=new");
//                intent.setData(content_url);
//                startActivity(intent);
                //获取相册权限
                PermissionUtils.verifyStoragePermissions(this);

                OpenCam();

                break;
        }
    }

    private void OpenCam() {
        Intent intentwa = new Intent(cxt, WebActivity.class);
        intentwa.putExtra("web_url", "https://btex.me/home/prove_tpl?window=new");
        startActivity(intentwa);
    }


    private void getData() {
        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(context);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(context, sp);
        RequestParams params = new RequestParams();
        params.addHeader("myclient", "android");
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_CHECKRP_TOKEN + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                mMicroAVLIDialog.dismiss();
                String result = responseInfo.result;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        String data = jsonObject.getString("data");
                        toAliyun(data);


                    } else {


                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });
    }

    private void toAliyun(String data) {

        RPSDK.start(data, context,
                new RPSDK.RPCompletedListener() {
                    @Override
                    public void onAuditResult(RPSDK.AUDIT audit) {


                        if (audit == RPSDK.AUDIT.AUDIT_PASS) {
                            //认证通过

                            getRen();


                        } else if (audit == RPSDK.AUDIT.AUDIT_FAIL) {
                            //认证不通过

                        } else if (audit == RPSDK.AUDIT.AUDIT_IN_AUDIT) {
                            //认证中，通常不会出现，只有在认证审核系统内部出现超时，未在限定时间内返回认证结果时出现。此时提示用户系统处理中，稍后查看认证结果即可。

                        } else if (audit == RPSDK.AUDIT.AUDIT_NOT) {
                            //未认证

                        } else if (audit == RPSDK.AUDIT.AUDIT_EXCEPTION) {
                            //系统异常

                        }
                    }
                });
    }


    private void getInfo() {

        String lang = "";
        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, sp);
        boolean isEngilsh = sp.getBoolean("isEngilsh", false);
        if (isEngilsh) {
            lang = "en";
        } else {
            lang = "zh_cn";
        }

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("lang", lang);
        params.addHeader("myclient", "android");
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MY_PROVE_INFO + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                mMicroAVLIDialog.dismiss();
                String result = responseInfo.result;
//                Log.i("wndqfhiuqdq", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        mGetInfo = new Gson().fromJson(result, GetInfo.class);
                        initviews(mGetInfo);

                    } else {

                        Toast.makeText(cxt, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBus(String event) {

        if ("AuthenticationInformationAcitvity".equals(event)) {
            getRen();
        }
        if ("CertificationOneActivityone".equals(event)) {
            getInfo();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public void getRen() {

        mMicroAVLIDialog.show();
        SharedPreferencesUtil sp = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, sp);
        RequestParams params = new RequestParams();
        params.addHeader("myclient", "android");
        params.addBodyParameter("origin", "ali_rp");

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.USER_PROVE_ACTION + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                mMicroAVLIDialog.dismiss();
                String result = responseInfo.result;
//                Log.i("nqkwjdnqwidhqw", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {

                        getInfo();

                    } else {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == 1) {
            // camear 权限回调

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // 表示用户授权
                OpenCam();

            } else {

                //用户拒绝权限
                Toast.makeText(this, "请同意授权,拒绝将无法使用", Toast.LENGTH_SHORT).show();

            }
        }

    }

}

